<template>
  <div id="homePage">
    <!-- 主页搜索框 -->
    <div class="search-bar">
      <a-form layout="inline" :model="searchParams" style="margin-top: 15px">
        <div class="firstSearchForm">
          <a-form-item class="category">
            <a-auto-complete
              v-model:value="searchParams.category"
              placeholder="热门图片分类"
              :options="categoryOptions"
              style="min-width: 180px"
              allow-clear
              @change="doSearch"
            />
          </a-form-item>
          <a-form-item>
            <a-select
              v-model:value="searchParams.tags"
              mode="tags"
              placeholder="热门图片标签"
              :options="tagOptions"
              style="min-width: 180px"
              allow-clear
              @change="doSearch"
            />
          </a-form-item>
          <a-form-item>
            <a-auto-complete
              v-model:value="searchParams.picFormat"
              placeholder="选择图片格式"
              :options="formatOptions"
              style="min-width: 181px"
              allow-clear
              @change="doSearch"
            />
          </a-form-item>
          <a-form-item>
            <a-input-number
              v-model:value="searchParams.picWidth"
              placeholder="宽度 8 - 20000"
              style="max-width: 180px"
              allow-clear
              @change="doSearch"
              :min="8"
              :max="20000"
              addon-after="像素"
            />
          </a-form-item>
          <a-form-item>
            <a-input-number
              v-model:value="searchParams.picHeight"
              placeholder="高度 8 - 20000"
              style="max-width: 180px"
              allow-clear
              @change="doSearch"
              :min="8"
              :max="20000"
              addon-after="像素"
            >
            </a-input-number>
          </a-form-item>
          <a-form-item>
            <a-input-number
              v-model:value="searchParams.picScale"
              placeholder="宽高比 0.1 - 10.0"
              style="max-width: 198px"
              allow-clear
              @change="doSearch"
              :min="0.1"
              :max="10.0"
              addon-after="宽/高"
            />
          </a-form-item>
        </div>
        <div class="secondSearchForm">
          <a-form-item class="search-text">
            <a-input
              v-model:value="searchParams.searchText"
              placeholder="合并搜索图片名称、简介、分类、标签"
              style="min-width: 340px"
              allow-clear
              size="large"
              @change="doSearch"
            />
          </a-form-item>
          <a-form-item>
            <a-input
              v-model:value="searchParams.name"
              placeholder="请输入图片名"
              style="min-width: 180px"
              allow-clear
              size="large"
              @change="doSearch"
            />
          </a-form-item>
          <a-form-item>
            <a-input
              v-model:value="searchParams.introduction"
              placeholder="请输入图片简介"
              style="min-width: 220px"
              allow-clear
              size="large"
              @change="doSearch"
            />
          </a-form-item>
          <a-form-item>
            <a-button
              :icon="h(ClearOutlined)"
              type="primary"
              @click="clearSearchParams"
              size="large"
              title="清空所有搜索和匹配条件，并刷新数据"
            >
              重置搜索或匹配
            </a-button>
          </a-form-item>
          <a-form-item class="refreshButton">
            <a-button
              :icon="h(ReloadOutlined)"
              type="primary"
              size="large"
              @click="refreshData"
              title="刷新数据，但是不清空搜索"
            >
              刷新列表
            </a-button>
          </a-form-item>
          <!-- 主色调搜索 -->
          <a-form-item label="主色调相似匹配" style="margin-top: 3px" title="匹配主色调相似的图片">
            <color-picker format="hex" @pureColorChange="onColorChange" />
          </a-form-item>
        </div>
      </a-form>
    </div>
    <!-- 分类和标签筛选菜单栏 -->
    <a-tabs v-model:active-key="selectedCategory" @change="doSearch">
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :tab="category" :key="category" />
    </a-tabs>
    <div class="tag-bar">
      <span style="margin-right: 6px">标签：</span>
      <a-checkable-tag
        v-for="(tag, index) in tagList"
        :key="tag"
        v-model:checked="selectedTagList[index]"
        @change="doSearch"
        style="margin-bottom: 5px"
      >
        {{ tag }}
      </a-checkable-tag>
    </div>
    <!-- 图片列表 -->
    <picture-list :dataList="dataList" :loading="loading" :publicFlag="publicFlag"/>
    <a-pagination
      style="text-align: center"
      show-quick-jumper
      v-model:current="searchParams.current"
      v-model:pageSize="searchParams.pageSize"
      :page-size-options="pageSizeOptions"
      :total="total"
      :show-total="showTotal"
      @change="onPageChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, h } from 'vue'
import {
  listPictureFormatUsingGet,
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import { ClearOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import PictureList from '@/components/PictureList.vue'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'

const route = useRoute()

// 快捷菜单栏
const categoryList = ref<string[]>([])
// 选中分类，默认为“全部”
const selectedCategory = ref<string>('all')
const tagList = ref<string[]>([])
// 选中标签
const selectedTagList = ref<boolean[]>([])

const publicFlag = ref<boolean>(true)

// 定义数据类型
const dataList = ref<API.PictureVO[]>([])
// 分页数据总数
const total = ref(0)
// 定义搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  // 从路由参数获取搜索文本
  searchText: (route.query.namePrefix as string) || '',
  // 从路由参数获取分类
  category: (route.query.category as string) || '',
  // 初始化为空数组
  tags: [],
  current: 1,
  pageSize: 18,
  sortField: '',
  sortOrder: 'descend',
})
const loading = ref(true)

// 判断 selectedTagList 中是否有值为 true 的元素
// @ts-ignore
const hasTrueValue = (tagList: Ref<boolean[]>) => {
  // @ts-ignore
  return tagList.value.some((item) => item === true)
}

// 根据搜索条件，远程获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    ...searchParams,
    // 复制 tags 数组，避免直接修改原始数据
    // @ts-ignore
    tags: [...searchParams.tags],
  }

  if (!searchParams.category && selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }

  if (hasTrueValue(selectedTagList)) {
    // 选中分类参数
    selectedTagList.value.forEach((useTag, index) => {
      if (useTag) {
        params.tags.push(tagList.value[index])
      }
    })
  }

  try {
    const res = await listPictureVoByPageUsingPost(params)
    if (res.data && res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      message.error('获取图片数据失败，' + (res.data?.message || ''))
    }
  } catch (error) {
    console.error('API 请求出错:', error)
    message.error('API 请求出错，请检查网络或联系管理员')
  }
  loading.value = false
}

// 首次进入图片管理页面，请求一次默认搜索的图片数据
onMounted(() => {
  fetchData()
})

// 展示总条数
const showTotal = (totalCount: number) => `共 ${totalCount} 张`

// 定义分页器参数
const onPageChange = (page: number, pageSize: number) => {
  searchParams.current = page
  searchParams.pageSize = pageSize
  fetchData()
}

// 定义每页数据量操作选项
const pageSizeOptions = ref<string[]>(['10', '18', '20', '30', '40', '50'])

/**
 * 搜索图片
 */
const doSearch = () => {
  if (searchParams.category) {
    selectedCategory.value = 'all'
  }
  // @ts-ignore
  if (searchParams.tags.length > 0) {
    selectedTagList.value = []
  }
  searchParams.current = 1
  fetchData()
}

// 默认展示图片分类、图片标签
const categoryOptions = ref<string[]>([])
const tagOptions = ref<{ value: string; label: string }[]>([])

/**
 * 用于搜索框默认展示图片分类、图片标签
 */
const getTagCategoryOptions = async () => {
  try {
    const res = await listPictureTagCategoryUsingGet()
    if (res.data && res.data.code === 0 && res.data.data) {
      tagOptions.value = (res.data.data.tagList || []).map((data) => ({
        value: data,
        label: data,
      }))
      tagList.value = res.data.data.tagList || []
      // @ts-ignore
      categoryOptions.value = (res.data.data.categoryList || []).map((data) => ({
        value: data,
        label: data,
      }))
      categoryList.value = res.data.data.categoryList || []
    } else {
      message.error('默认分类标签列表展示失败，' + (res.data?.message || ''))
    }
  } catch (error) {
    console.error('获取分类标签选项出错:', error)
    message.error('获取分类标签选项出错，请检查网络或联系管理员')
  }
}

// 默认展示图片格式
const formatOptions = ref<{ value: string; label: string }[]>([])

/**
 * 用于搜索框默认展示图片格式
 */
const getFormatOptions = async () => {
  try {
    const res = await listPictureFormatUsingGet()
    if (res.data && res.data.code === 0 && res.data.data) {
      formatOptions.value = (res.data.data.formatList || []).map((data) => ({
        value: data,
        label: data,
      }))
    } else {
      message.error('图片格式列表展示失败，' + (res.data?.message || ''))
    }
  } catch (error) {
    console.error('获取图片格式选项出错:', error)
    message.error('获取图片格式选项出错，请检查网络或联系管理员')
  }
}

onMounted(() => {
  getTagCategoryOptions()
  getFormatOptions()
})

const refreshData = async () => {
  await fetchData()
  message.success('刷新成功，图片库已是最新数据咯')
}

/**
 * 重置搜索或匹配条件
 */
const clearSearchParams = () => {
  // 因为 SearchParams 是 reactive 对象
  // 所以不要直接置为空对象，最好是把每个字段值设置为 undefined 或空数组
  Object.keys(searchParams).forEach((key) => {
    searchParams[key as keyof typeof searchParams] = undefined
  })
  searchParams.tags = []
  selectedCategory.value = 'all'
  selectedTagList.value = []
  // 从路由参数获取搜索文本
  searchParams.searchText = (route.query.namePrefix as string) || ''
  // 从路由参数获取分类
  searchParams.category = (route.query.category as string) || ''
  // 初始化为空数组
  searchParams.tags = []
  searchParams.current = 1
  searchParams.pageSize = 18
  searchParams.sortField = ''
  searchParams.sortOrder = 'descend'
  // 清空后要通知父组件执行搜索
  fetchData()
  message.success('搜索条件或匹配方式已重置')
}

/**
 * 主色调搜索相似图片
 * @param color
 */
const onColorChange = async (color: string) => {
  loading.value = true
  const res = await searchPictureByColorUsingPost({
    picColor: color,
    // @ts-ignore
    spaceId: null,
  })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? []
    dataList.value = data
    total.value = data?.length
    message.success('匹配主色调相似图片成功，至多匹配18张图片')
  } else {
    message.error('匹配失败，' + res.data.message)
  }
  loading.value = false
}
</script>

<style scoped>
#homePage {
  margin-bottom: 16px;
}

.search-bar {
  margin: 0 auto 16px;
}

.firstSearchForm {
  display: flex;
  margin: 10px auto;
}

.secondSearchForm {
  display: flex;
  margin: auto;
}

.search-text {
  margin-right: 25px;
  margin-bottom: 8px;
}

.category {
  margin-right: 25px;
  margin-bottom: 8px;
}

.tag-bar {
  margin-bottom: 20px;
}
</style>
